let express = require('express')
let websocket = require('ws')

let app = express()
let wss = new websocket.Server({ port: 8080 })

wss.on('connection', (ws) => {
    console.log('socket 已启动');

    ws.on('message', (message) => {
        console.log("receive: ", Buffer.from(message).toString());
        let data = JSON.parse(Buffer.from(message).toString());

        console.log("parse message:", data);

        wss.clients.forEach((client) => {
            client.send(JSON.stringify({ data }));
        })
    });

    ws.on('close', function close() {
        console.log('client disconnected');
    });
})

app.listen(3000, () => {
    console.log('express 启动')
})